const app = getApp()
const utils = require("../../../utils/util")

Page({
    data: {
        swiperList: [       // 轮播图数据
            {
                id: 1,
                url: "/static/icon/tabBar_car.png"
            },
            {
                id: 2,
                url: "/static/icon/tabBar_news.png"
            },
            {
                id: 3,
                url: "/static/icon/tabBar_people.png"
            }
        ],


        isAddBusiness: false,    // 是否打开 ’发起拼车‘页面, true为打开状态, false为关闭状态
        isStart: false,         // 是否打开 ’选择起点‘页面
        isTerminal: false,      // 是否打开 ’选择终点‘页面
        isSelection: false,     // 是否打开 ’查找拼车‘页面
        start: "广西民族大学东校区", // 起点
        terminal: "广西大学",      //终点
        /** 发起拼车详情页的表单数据 */
        formData: {
            start: "",
            terminal: "",
            carNumber: "",      // 车牌号
            phoneNumber: "",
            date: "选择日期",
            startTime: "选择时间",
            endTime: "选择时间",
            stopTime: "选择时间",   //拼车结束
            peopleNumber: "请选择拼车人数"
        },
        stopTimeTamp: "12:00",           // stopTime 的时间格式 如13:00
        date_start: "2022-08-15",   // 拼车日期的范围
        date_end: "2023-08-15",     // 拼车日期的范围
        togetherSelect_start: false,      // 发车时间是否都已经选择
        togetherSelect_end: false,      // 发车时间是否都已经选择
        startTime_start: "00:00",       // 限制 startTime 的范围
        startTime_end: "23:59", // startTime_end 限制 startTime 的范围
        endTime_start: "00:00", // 限制 endTime 的范围
        peopleNumberArray: [2, 3, 4],   // 选择拼车人数
        detectionForm: [null,"warn","warn","warn","warn","warn","warn"],    // 发起拼车详情页 的 icon 的 type, warn错误, success正确, 第一项null 给 '地址' 预留的
        inputValues: "",    // 查找拼车详情页的输入框的值
        selectList: [],     // 根据’地址名‘关键字，检索到的拼车信息


        /** 最新发布的列表数据 */
        releaseList: [
            {
                id: 1,
                url: "/static/image/first.png",
                start: "民大",
                terminal: "西大",
                title: "民大 --> 西大",
                date: "2022/08/08",
                startTime: "19:30",
                endTime: "19:40",
                time: "19:30~19:40",
                stopTime: "",       // 发起拼车的时限
                phoneNumber: "",
                hasCar: false,      // true已约车 false未约车
                carNumber: "",      // 空为未约车
                views: "1",
                avatar: ["/static/icon/tabBar_car.png","/static/image/first.png"],
                peopleNumber: 3,    // 拼车的满载人数
                nowPeopleNumber: 2, // 已经加入拼车的人数
                originator: {       // 拼车的发起人
                    userId: 1,
                    nickname: "刘备",
                    avatar: "/static/icon/tabBar_car.png"
                },
                members: [          // 包括发起人在内，参与拼车的人
                    {
                        userId: 1,
                        nickname: "刘备",
                        avatar: "/static/icon/tabBar_car.png"
                    },
                    {
                        userId: 2,
                        nickname: "关羽",
                        avatar: "/static/image/first.png"
                    }
                ]
            },
            {
                id: 2,
                url: "/static/image/first.png",
                start: "民大",
                terminal: "西大",
                title: "民大 --> 西大",
                date: "2022/08/08",
                startTime: "19:30",
                endTime: "19:40",
                time: "19:30~19:40",
                stopTime: "",       // 发起拼车的时限
                phoneNumber: "",
                hasCar: true,      // true已约车 false未约车
                carNumber: "桂A-88888",      // 空为未约车
                views: "1",
                avatar: ["/static/icon/tabBar_car.png"],
                peopleNumber: 3,    // 拼车的满载人数
                nowPeopleNumber: 1, // 已经加入拼车的人数
                originator: {       // 拼车的发起人
                    userId: 1,
                    nickname: "刘备",
                    avatar: "/static/icon/tabBar_car.png"
                },
                members: [          // 包括发起人在内，参与拼车的人
                    {
                        userId: 1,
                        nickname: "刘备",
                        avatar: "/static/icon/tabBar_car.png"
                    }
                ]
            },
            {
                id: 3,
                url: "/static/image/first.png",
                start: "民大",
                terminal: "西大",
                title: "民大 --> 西大",
                date: "2022/08/08",
                startTime: "19:30",
                endTime: "19:40",
                time: "19:30~19:40",
                stopTime: "",       // 发起拼车的时限
                phoneNumber: "",
                hasCar: false,      // true已约车 false未约车
                carNumber: "",      // 空为未约车
                views: "1",
                avatar: ["/static/icon/tabBar_car.png"],
                peopleNumber: 2,    // 拼车的满载人数
                nowPeopleNumber: 2, // 已经加入拼车的人数
                originator: {       // 拼车的发起人
                    userId: 1,
                    nickname: "刘备",
                    avatar: "/static/icon/tabBar_car.png"
                },
                members: [          // 包括发起人在内，参与拼车的人
                    {
                        userId: 1,
                        nickname: "刘备",
                        avatar: "/static/icon/tabBar_car.png"
                    },
                    {
                        userId: 3,
                        nickname: "张飞",
                        avatar: "/static/icon/tabBar_people.png"
                    }
                ]
            }
        ],
        /** '最新发布'列表的按钮禁用 */
        joinCarpooling_btn: {
            isDisable: [],
            btnText: []
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(){
        // 渲染按钮的禁用
        this.joinCarpooling_btn_disabled()

        // 发起拼车表单可输入的日期范围
        this.setFormDate()

        // 发起拼车表单可输入的时间初值
        this.setFormStartTime_start()

    },


    /**
     * 页面： ’拼车模块‘
     * 功能：交换起始点
     * */
    swapPlace: function () {
        let swap =this.data.start
        this.setData({
            start: this.data.terminal,
            terminal: swap
        })
    },


    /**
     * 页面: '拼车模块'
     * 功能：点击按钮打开页面，以及点返回按钮关闭页面
     * */
    addBusiness: function () {
        this.setData({
            isAddBusiness: true
        })
    },
    openSelectStartView: function(){
        let that = this
        wx.chooseLocation({
            success(res){
                that.setData({
                    start: res.address
                })
            }
        })
    },
    openSelectTerminalView: function(){
        let that = this
        wx.chooseLocation({
            success(res){
                that.setData({
                    terminal: res.address
                })
            }
        })
    },
    openSelectView: function(){
        this.setData({
            isSelection: true
        })
    },
    back: function(){
        this.setData({
            isAddBusiness: false,
            isStart: false,
            isTerminal: false,
            isSelection: false
        })
    },


    /**
     * 页面：’拼车模块‘ -> ’发起拼车‘
     * 功能：1.表单的组件的监听。  2.保存拼车信息到 releaseList
     * */
    setDetectionForm: function(index, value){
        switch (value) {
            case "success":
                this.setData({
                    ['detectionForm['+ index + ']']: "success"
                })
                break;
            case "warn":
                this.setData({
                    ['detectionForm['+ index + ']']: "warn"
                })
                break;
        }
    },
    setFormDate: function(){
        // 拼车日期的范围 当前日期 ~ 当前日期+1年
        let myDate = new Date()
        let year = myDate.getFullYear()
        let month = myDate.getMonth() + 1
        let day = myDate.getDate()
        this.setData({
            date_start: year + "-" + month + "-" + day,
            date_end: (year+1) + "-" + month + "-" + day,
        })
    },
    setFormStartTime_start: function(){
        let myDate = new Date()
        let hours = myDate.getHours()
        let min = myDate.getMinutes()
        this.setData({
            startTime_start: hours + ":" + min
        })
    },
    getCarNumber: function(e){
        const regex = '[\u4e00-\u9fa5][A-Z][-][A-z0-9]{5}'
        let flag = e.detail.value.match(regex);
        if(flag){
            this.setDetectionForm(1, "success")
        }else{
            this.setDetectionForm(1, "warn")
        }
    },
    getPhoneNumber: function(e){
        const regex = '[1-9][0-9]{10}'
        let flag = e.detail.value.match(regex);
        if(flag){
            this.setDetectionForm(2, "success")
        }else{
            this.setDetectionForm(2, "warn")
        }
    },
    bindDateChange: function(e){
          this.setData({
              ['formData.date']: e.detail.value
          })
        this.setDetectionForm(3, "success")
    },
    bindTimeChange_start: function(e){
        this.setData({
            endTime_start: e.detail.value
        })
        this.setData({
            ['formData.startTime']: e.detail.value
        })
        this.data.togetherSelect_start = true
        if(this.data.togetherSelect_start && this.data.togetherSelect_end){
            this.setDetectionForm(4, "success")
        }else{
            this.setDetectionForm(4, "warn")
        }
    },
    bindTimeChange_end: function(e){
        this.setData({
            startTime_end: e.detail.value
        })
        this.setData({
            ['formData.endTime']: e.detail.value
        })
        this.data.togetherSelect_end = true
        if(this.data.togetherSelect_start && this.data.togetherSelect_end){
            this.setDetectionForm(4, "success")
        }else{
            this.setDetectionForm(4, "warn")
        }
    },
    bindTimeChange_stop: function(e){
        let time = e.detail.value
        let hours = time.substring(0,2)
        let min = time.substring(3,5)
        this.setData({
            stopTimeTamp: time
        })
        this.setData({
            ['formData.stopTime']: hours + "小时" + min + "分钟"
        })
        this.setDetectionForm(5, "success")
    },
    bindPeopleNumberChange: function(e){
        this.setData({
            ['formData.peopleNumber']: this.data.peopleNumberArray[e.detail.value]
        })
        this.setDetectionForm(6, "success")
    },
    handleForm: function(e){
        let detectionForm = this.data.detectionForm
        let len = detectionForm.length
        let flag = false
        for(let i=1; i<len; i++){
            if(detectionForm[i] === "warn"){
                wx.showToast({
                    title: '信息填写不完整',
                    icon: 'none',
                    duration: 1500//持续的时间
                })
                break;
            }else{
                if(i == len-1){
                    flag = true
                    wx.showToast({
                        title: '发起拼车成功',
                        icon: 'success',
                        duration: 1500//持续的时间
                    })
                }
            }
        }
        if(flag){
            let list = this.data.releaseList
            let object={
                id: this.data.releaseList.length + 1,
                url: "/static/image/first.png",
                start: this.data.start,
                terminal: this.data.terminal,
                title: this.data.start + "-->" + this.data.terminal,
                date: e.detail.value.date,
                startTime: e.detail.value.startTime,
                endTime: e.detail.value.endTime,
                time: e.detail.value.startTime + "~" + e.detail.value.endTime,
                stopTime: e.detail.value.stopTime,          // xx时xx分xx秒
                stopTimeTamp: this.data.stopTimeTamp,       // 时间格式 如 12:30:00
                views: "0",
                avatar: [app.data.userInfo.avatar],
                peopleNumber: e.detail.value.peopleNumber,
                nowPeopleNumber: 1,
                originator: app.data.userInfo,
                members: [app.data.userInfo]
            }
            list.unshift(object)
            this.setData({
                releaseList: list
            })
            // 渲染按钮的禁用
            this.joinCarpooling_btn_disabled()
            this.back()
        }

    },


    /**
     * 页面: ’拼车模块‘ -> '查找拼车'
     * 功能：输入地址的关键字，检索后显示出来
     * */
    getInputValue: function(e){
        this.setData({
            inputValues: e.detail.value
        })
    },
    search: function(){
        let len = this.data.releaseList.length
        let list = []
        for(let i=0; i<len; i++){
            let title = this.data.releaseList[i].title
            let isInclude = title.includes(this.data.inputValues);
            if(isInclude && this.data.inputValues.length > 0){
                list.push(this.data.releaseList[i])
            }
        }
        this.setData({
            selectList: list,
        })
    },

    /**
     * 页面：’最新发布列表‘
     * 功能：点击按钮加入拼车，改变人数显示，将按钮禁用
     * */
    joinCarpooling: function (e) {
        // 读取 data-value 传进来的数组下标 index
        // console.log(e.currentTarget.dataset.value)
        let index = e.currentTarget.dataset.value
        let members = this.data.releaseList[index].members
        let len = members.length
        let joined = false
        for(let i=0; i<len; i++){
            if(app.data.userInfo.userId == members[i].userId){
                joined = true
            }
        }
        if(joined){
            console.log("您已经加入了该拼车")
        }else{
            let nowPeopleNumber = this.data.releaseList[index].nowPeopleNumber
            let peopleNumber = this.data.releaseList[index].peopleNumber
            if(nowPeopleNumber < peopleNumber){
                members.push(app.data.userInfo)
                this.setData({
                    ['releaseList[' + index + '].members']: members,
                    ['releaseList[' + index + '].nowPeopleNumber']: nowPeopleNumber + 1,
                    ['joinCarpooling_btn.isDisable[' + index + ']']: true,
                    ['joinCarpooling_btn.btnText[' + index + ']']: "已加入"
                })
                wx.navigateTo({
                    url: '/pages/navigation/index/joincar' + '?releaseItem=' +  JSON.stringify(this.data.releaseList[index])
                })
            }else{
                console.log("该拼车人满了")
            }
        }
    },
    // 禁用“立即拼车”按钮
    joinCarpooling_btn_disabled: function () {
        let isDisable = []
        let btnText = []
        let releaseList= this.data.releaseList
        let len = releaseList.length
        for(let i=0; i<len; i++){
            let members = releaseList[i].members
            let len_mb = members.length
            for(let j=0; j<len_mb; j++){
                if(app.data.userInfo.userId == members[j].userId){
                    isDisable.push(true)
                    btnText.push("已加入")
                    break
                }
                if(j == len_mb-1){
                    isDisable.push(false)
                    btnText.push("立即加入")
                }
            }
        }
        this.setData({
            ['joinCarpooling_btn.isDisable']: isDisable,
            ['joinCarpooling_btn.btnText']: btnText
        })
    }



})